package com.tj.jinzao.activity;


import android.app.Activity;
import android.content.Intent;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tj.jinzao.R;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.callback.IUploadView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.Target;
import com.tj.jinzao.model.User;
import com.tj.jinzao.presenter.UserPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.widgets.ChooseBottomDialog;
import com.tj.jinzao.widgets.MaxTextLengthFilter;
import com.tj.jinzao.widgets.RoundedImageView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;

/**
 * 个人资料页面
 * Created by wjy on 2019/1/5.
 */
public class PersonInfoActivity extends BaseActivity implements IUploadView<List<User>> {

    @BindView(R.id.iv_head)
    RoundedImageView mHeadView;
    @BindView(R.id.et_name)
    EditText mNameView;
    @BindView(R.id.tv_birthday)
    TextView mBirthDayView;
    @BindView(R.id.tv_gender)
    TextView mGenderView;
    @BindView(R.id.et_city)
    EditText mCityView;
    @BindView(R.id.et_intro)
    EditText mIntroView;
    @BindView(R.id.tv_target)
    TextView mTargetView;
    @BindView(R.id.tv_health)
    EditText mHealthView;
    @BindView(R.id.tv_status)
    TextView mStatusView;
    @BindView(R.id.tv_case)
    TextView mCaseView;
    @BindView(R.id.back_lay)
    LinearLayout back_lay;
    @BindView(R.id.config)
    TextView config;
    @BindView(R.id.target_lay)
    RelativeLayout target_lay;
    @BindView(R.id.body_lay)
    RelativeLayout body_lay;
    @BindView(R.id.bls_lay)
    RelativeLayout bls_lay;

    private String mImagePath;

    private UserPresenter mPresenter;

    @Override
    public int getLayoutResource() {
        return R.layout.activity_me_detail;
    }
    User user;
    @Override
    protected void setupView() {
        super.setupView();
        user = UserManager.getInstance().getUser();

        Glide.with(this).load(Constant.IMAGE_PREFIX+user.getImgurl()).into(mHeadView);
        mNameView.setText(user.getNickname());
        mBirthDayView.setText(user.getBirthday());
        mGenderView.setText(user.getGender() == 1 ? "男" : "女");
        mCityView.setText(user.getPermanentResidence());
        mIntroView.setText(user.getSignature());
        mTargetView.setText(user.getPersonalGoal());
        mStatusView.setText(user.getPhysicalConditions());
        mHealthView.setText(user.getFamilyHealth());
        mPresenter = new UserPresenter(this);
        mNameView.setFilters(new InputFilter[]{new MaxTextLengthFilter(12,PersonInfoActivity.this,"昵称限12字以内")});
        mIntroView.setFilters(new InputFilter[]{new MaxTextLengthFilter(20,PersonInfoActivity.this,"个性签名限20字以内")});

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mPresenter==null){
            return;
        }
        mPresenter.getBLList();

    }


    @OnClick(R.id.back_lay)
    public void backLay(){
        finish();
    }
    @OnClick(R.id.config)
    public void config(){
        upload();
    }
    @OnClick(R.id.target_lay)
    public void target_lay(){
        Intent to=new Intent();
        to.putExtra("mStep",6);
        to.putExtra("mType",2);
        to.setClass(this,CompleteInfoActivity.class);
        startActivityForResult(to,101);
    }
    @OnClick(R.id.body_lay)
    public void body_lay(){
        Intent to=new Intent();
        to.putExtra("mStep",7);
        to.putExtra("mType",3);
        to.setClass(this,CompleteInfoActivity.class);
        startActivityForResult(to,102);
    }
    @OnClick(R.id.bls_lay)
    public void bls_lay(){
        Intent to=new Intent();
        to.putExtra("position",1);
        to.putExtra("userId",String.valueOf(user.getId()));
        to.setClass(this,MyHealthCaseActivity.class);
        startActivity(to);
    }


    @OnClick(R.id.ll_head_layout)
    public void chooseHead() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .compress(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @OnClick(R.id.rl_gender_layout)
    public void chooseGender() {
//        ChooseBottomDialog dialog = new ChooseBottomDialog(this);
//        List<String> genderList = new ArrayList();
//        genderList.add("男");
//        genderList.add("女");
//        dialog.setData(genderList, null, null, mGenderView.getText().toString().trim(), null, null);
//        dialog.setValueListener(new ChooseBottomDialog.OnWheelValueListener() {
//            @Override
//            public void onValueChanged(String select1, String select2, String select3) {
//                mGenderView.setText(select1);
//            }
//
//            @Override
//            public void onValueChanging(int selectIndex, int wheelIndex) {
//
//            }
//        });
//        dialog.show();
    }

    @OnClick(R.id.rl_birthday_layout)
    public void chooseBirthDay() {
        ChooseBottomDialog dialog = new ChooseBottomDialog(this);
        Calendar calendar = Calendar.getInstance();
        List<String> yearList = new ArrayList();
        for (int i = 1900; i <= calendar.get(Calendar.YEAR)+1; i++) {
            yearList.add(String.valueOf(i));
        }
        List<String> monthList = new ArrayList();
        for (int i = 1; i < 13; i++) {
            monthList.add(String.valueOf(i));
        }
        List<String> dayList = new ArrayList();
        for (int i = 1; i < 32; i++) {
            dayList.add(String.valueOf(i));
        }
        dialog.setValueListener(new ChooseBottomDialog.OnWheelValueListener() {
            @Override
            public void onValueChanged(String select1, String select2, String select3) {
                mBirthDayView.setText(select1 + "-" + select2 + "-" + select3);
            }

            @Override
            public void onValueChanging(int selectIndex, int wheelIndex) {

            }
        });
        dialog.setData(yearList, monthList, dayList, String.valueOf(calendar.get(Calendar.YEAR))
                , String.valueOf(calendar.get(Calendar.MONTH) + 1)
                , String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
        dialog.show();
    }


    private void upload() {
        User user = UserManager.getInstance().getUser();
        Map<String, Object> map = new HashMap();
        if (!TextUtils.isEmpty(mImagePath)) {
            if (mImagePath.startsWith(Constant.SD_ROOT)) {
                mPresenter.uploadFile(mImagePath);
                return;
            }
            map.put("imgurl", mImagePath);
        }
        String nickName = mNameView.getText().toString().trim();
        if (!TextUtils.equals(nickName, user.getNickname())) {
            map.put("nickname", nickName);
        }
        String birthday = mBirthDayView.getText().toString().trim();
        if (!TextUtils.equals(birthday, user.getBirthday())) {
            map.put("birthday", birthday);
        }
        int gender = TextUtils.equals(mGenderView.getText().toString().trim(), "男") ? 0 : 1;
        if (gender != user.getGender()) {
            map.put("gender", gender);
        }
        String city = mCityView.getText().toString().trim();
        if (!TextUtils.equals(city, user.getPermanentResidence())) {
            map.put("permanentResidence", city);
        }
        String signature = mIntroView.getText().toString().trim();
        if (!TextUtils.equals(signature, user.getSignature())) {
            map.put("signature", signature);
        }
        String personalGoal = mTargetView.getText().toString().trim();
        if (!TextUtils.equals(signature, user.getPersonalGoal())) {
            map.put("personalGoal", personalGoal);
        }
        String physicalConditions = mStatusView.getText().toString().trim();
        if (!TextUtils.equals(signature, user.getPhysicalConditions())) {
            map.put("physicalConditions", physicalConditions);
        }
        if (!TextUtils.isEmpty(mHealthView.getText())&&!TextUtils.equals(mHealthView.getText().toString(), user.getFamilyHealth())) {
            map.put("familyHealth", mHealthView.getText().toString());
        }

        Log.w("用户信息图片上传",""+map.toString());

        if (map.size() > 0) {
            mPresenter.updateInfo(PersonInfoActivity.this,map);
        } else {
            super.clickLeftButton();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.detachView();
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @Override
    public Activity getContext() {
        return this;
    }

    @Override
    public void onRequestSuccess(List<User> users) {
        ToastUtils.showToast(this, "更新成功");
        finish();
    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {

    }

    @Override
    public void onUploadSuccess(String path, String url) {
        mImagePath = url;
        upload();

    }
    private String bls="";

    @Override
    public void onCaseSuccess(List<Target> list) {
        bls="";
        for (int i=0;i<list.size();i++){
            if(i==0){
                bls=bls+list.get(i).getName();
            }else {
                bls=bls+","+list.get(i).getName();
            }
        }
        mCaseView.setText(bls);
    }

    @Override
    public void onCaseFailed(String msg) {
        mCaseView.setText("暂无病例史");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia localMedia : selectList) {
                        mImagePath = localMedia.isCompressed() ? localMedia.getCompressPath() : localMedia.getPath();
                        Glide.with(this).load(mImagePath).into(mHeadView);
                    }
                    break;
                case 101:
                    try {
                        String target=data.getStringExtra("contentTarget");
                        user.setPersonalGoal(target);
                        mTargetView.setText(target);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    break;
                case 102:
                    try {
                        String contentBody=data.getStringExtra("contentBody");
                        user.setPhysicalConditions(contentBody);
                        mStatusView.setText(contentBody);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    break;
            }
        }
    }
}
